package com.mybatis.controller;

import com.mybatis.dto.request.CodeGenerationParam;
import com.mybatis.dto.request.DatabaseParam;
import com.mybatis.dto.request.QueryGenerationParam;
import com.mybatis.message.ReturnResult;
import com.mybatis.service.GeneratorCodeLogService;
import com.mybatis.service.GeneratorService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;

/**
 * @desc: 代码生成相关api
 * @projectName: mybatis-generator-parent
 * @author: xhs
 * @date: 2023-7-22 15:15
 * @version: JDK 1.8
 */
@Validated
@RestController
@RequestMapping("/generator")
public class GeneratorController {
    @Resource
    private GeneratorService generatorService;
    @Resource
    private GeneratorCodeLogService codeLogService;

    /**
     * 数据库连接测试
     *
     * @param databaseParam 数据库连接入参
     * @return ReturnResult
     */
    @PostMapping("/databaseConnection")
    public ReturnResult<Object> databaseConnection(@Valid @RequestBody DatabaseParam databaseParam) {
        return generatorService.databaseConnection(databaseParam);
    }

    /**
     * 获取数据库所有表名称
     *
     * @param databaseParam 数据库连接入参
     * @return ReturnResult
     */
    @PostMapping("/getTableNameList")
    public ReturnResult<Object> getTableNameList(@Valid @RequestBody DatabaseParam databaseParam) {
        return generatorService.getTableNameList(databaseParam);
    }

    /**
     * 代码生成
     *
     * @param codeGenerationParam 代码生成入参
     * @return ReturnResult
     */
    @PostMapping("/codeGeneration")
    public ReturnResult<Object> codeGeneration(@RequestBody CodeGenerationParam codeGenerationParam) {
        return generatorService.codeGeneration(codeGenerationParam);
    }

    /**
     * 下载生成的代码
     *
     * @param fileUrl  文件路径
     * @param response response
     */
    @GetMapping("/downloadCode")
    public void downloadCode(HttpServletResponse response, @NotEmpty(message = "文件路径不能为空") String fileUrl) {
        generatorService.downloadCode(response, fileUrl);
    }

    /**
     * 分页查询代码生成记录
     *
     * @param generationParam 查询条件
     * @return ReturnResult<Object>
     */
    @PostMapping("/queryGenerationLog")
    public ReturnResult<Object> queryGenerationLog(@RequestBody QueryGenerationParam generationParam) {
        return codeLogService.queryGenerationLog(generationParam);
    }
}
